flutter Future and FutureBuilder for string (not obj)

hur-kyuh-leez·2022년 4월 20일
0

if backend api gives only specific column data,
then we need to take care of the data different.
it's actually easier then normal json data.
you dont need to make an object(class).

let's re-use codes from official cookbook

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


///
/// backend api gives only one column data by pluck().
/// below code take cares of data(string) and display it
///

Future<String> fetchAlbum(String name) async {
  final response = await http
      .get(Uri.parse('http://127.0.0.1:8000/api/product/$name'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.

    var responseString = jsonDecode(response.body)[0];
    return responseString;


  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}




void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<String> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum('SA215-MBK (소형볼)');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                // print(snapshot.data?[0]['id']);
                final returnThis = snapshot.data?.toString() ?? 'No data';
                return Text(returnThis);


              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

we only had to take care of changing Future types. The best part is we don't need to make a custom object in order to store json data.

profile
벨로그에 생각을 임시로 저장합니다. 틀린건 틀렸다고 해주세요 :) 그래야 논리 학습이 강화됩니다.

0개의 댓글