0

flutter http パッケージを使用して、フラッター内でネットワーク リクエストに取り組んでいます。

これまでのところ、ようこそ画面とネットワーク ヘルパーがあります。

ウェルカム画面には、リスト ビューと下部バーを備えた足場があります。

リスト ビューには、リスト アイテムごとにテキストと画像が表示されます。

これらのアイテムのデータは、HTTP リクエストから取得されます。

その要求は、私のネットワーク ヘルパー クラスで行われます。

ようこそ画面には、ネットワーク ヘルパーから返された json にローカル変数を設定する initState() から呼び出す関数がありますが、変数からデータにアクセスしようとすると、null になります。ただし、代わりにデータを印刷するだけであれば、データはそこにあります。

私の問題は、データにアクセスしたことですが、そのデータをリスト ビューに渡す方法が思い浮かびません。

私のネットワークヘルパークラスコードは次のようになります

import 'package:http/http.dart' as http;
import 'dart:convert';

class NetworkHelper{
  //Sets up search filter variables
  int year;
  String make;
  String model;
  String condition;
  String combustible;
  String style;
  String color;
  double minPrice;
  double maxPrice;

  Future fetchAlbum() async {
    http.Response response = await http.get('https://jsonplaceholder.typicode.com/todos');

    if (response.statusCode == 200) {
      String data = response.body;
      return jsonDecode(data);
    } else {
      throw Exception('Failed to load album');
    }
  }


}

そして、これが私のウェルカム画面の外観です

import 'package:flutter/material.dart';
import 'package:components/appBarTitle.dart';
import 'package:components/bottomBarComponent.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:constants.dart';
import 'package:helpers/network_helper.dart';
import 'dart:convert';

class WelcomeScreen extends StatefulWidget {
  static String id = '/welcome_screen';
  @override
  _WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {

  int _index = 0;

  NetworkHelper http = NetworkHelper();
  dynamic data;
  Future testMethod () async {
    this.data = await http.fetchAlbum();
    print(this.data);
  }

  @override
  void initState() {
    super.initState();
    testMethod();
  }

  @override
  Widget build(BuildContext context) {


    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0.0,
        title: AppBarTitle(),
      ),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: ListView(
          children: [
            ListBody(
              children: [
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                ),
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                ),
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                ),
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                ),
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                ),
                Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('2017 Nissan', style: TextStyle(fontWeight: FontWeight.w300,)),
                            Text('Versa 1.6 SL', style: TextStyle(fontWeight: FontWeight.w100,)),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text('\$7,998.00', style: TextStyle(fontWeight: FontWeight.w200,)),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Image.network('https://via.placeholder.com/450/0000FF', scale: 4,),

                      ),

                    ],
                  ),
                )
              ],
            ),

          ],
        ),
      ),
        bottomNavigationBar: ConvexAppBar(
          backgroundColor: Color(0xffe74c3c),
          items: [
            TabItem(icon: Icons.home, title: 'Home'),
            TabItem(icon: Icons.map, title: 'Discover'),
            TabItem(icon: Icons.search, title: 'Busca'),
            TabItem(icon: Icons.person, title: 'Mi Cuenta'),
            TabItem(icon: Icons.build, title: 'Settings'),
          ],
          initialActiveIndex: 2,//optional, default as 0
          onTap: (int i) => print('click index=$i'),
        )
    );
  }
}
4

2 に答える 2

1

以下の完全なコードをコピーして貼り付けて実行
できます使用できFutureBuilder、 コードスニペットのListView.builder
下に動作するデモを見ることができます

Future<List<Payload>> _future;
NetworkHelper http = NetworkHelper();
Future<List<Payload>> testMethod() async {
    var data = await http.fetchAlbum();
    return data;
}

@override
void initState() {
    super.initState();
    _future = testMethod();
}
...  
FutureBuilder(
          future: _future,
          builder: (context, AsyncSnapshot<List<Payload>> snapshot) {
            ...
                } else {
                  return ListView.builder(
                      shrinkWrap: true,
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return Card(
                          elevation: 6.0,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 6.0,
                                bottom: 6.0,
                                left: 8.0,
                                right: 8.0),
                            child: ListTile(
                              title: Text(
                                  snapshot.data[index].id.toString()),
                              subtitle: Text(
                                snapshot.data[index].title,
                              ),

動作デモ

ここに画像の説明を入力

完全なコード

import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

List<Payload> payloadFromJson(String str) =>
    List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));

String payloadToJson(List<Payload> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Payload {
  Payload({
    this.userId,
    this.id,
    this.title,
    this.completed,
  });

  int userId;
  int id;
  String title;
  bool completed;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        completed: json["completed"],
      );

  Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "completed": completed,
      };
}

class NetworkHelper {
  //Sets up search filter variables
  int year;
  String make;
  String model;
  String condition;
  String combustible;
  String style;
  String color;
  double minPrice;
  double maxPrice;

  Future<List<Payload>> fetchAlbum() async {
    http.Response response =
        await http.get('https://jsonplaceholder.typicode.com/todos');

    if (response.statusCode == 200) {
      //String data = response.body;
      return payloadFromJson(response.body);
    } else {
      throw Exception('Failed to load album');
    }
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: WelcomeScreen(),
    );
  }
}

class WelcomeScreen extends StatefulWidget {
  static String id = '/welcome_screen';
  @override
  _WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {
  int _index = 0;
  Future<List<Payload>> _future;

  NetworkHelper http = NetworkHelper();

  Future<List<Payload>> testMethod() async {
    var data = await http.fetchAlbum();
    return data;
  }

  @override
  void initState() {
    super.initState();
    _future = testMethod();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          elevation: 0.0,
          title: Text("title"),
        ),
        body: Column(
          children: [
            Expanded(
              flex: 1,
              child: FutureBuilder(
                  future: _future,
                  builder: (context, AsyncSnapshot<List<Payload>> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                        return Text('none');
                      case ConnectionState.waiting:
                        return Center(child: CircularProgressIndicator());
                      case ConnectionState.active:
                        return Text('');
                      case ConnectionState.done:
                        if (snapshot.hasError) {
                          return Text(
                            '${snapshot.error}',
                            style: TextStyle(color: Colors.red),
                          );
                        } else {
                          return ListView.builder(
                              shrinkWrap: true,
                              itemCount: snapshot.data.length,
                              itemBuilder: (context, index) {
                                return Card(
                                  elevation: 6.0,
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        top: 6.0,
                                        bottom: 6.0,
                                        left: 8.0,
                                        right: 8.0),
                                    child: ListTile(
                                      title: Text(
                                          snapshot.data[index].id.toString()),
                                      subtitle: Text(
                                        snapshot.data[index].title,
                                      ),
                                    ),
                                  ),
                                );
                              });
                        }
                    }
                  }),
            ),
            Expanded(
              flex: 1,
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    ListBody(
                      children: [
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Card(
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  children: [
                                    Text('2017 Nissan',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w300,
                                        )),
                                    Text('Versa 1.6 SL',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w100,
                                        )),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text('\$7,998.00',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w200,
                                          )),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Image.network(
                                  'https://via.placeholder.com/450/0000FF',
                                  scale: 4,
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        bottomNavigationBar: ConvexAppBar(
          backgroundColor: Color(0xffe74c3c),
          items: [
            TabItem(icon: Icons.home, title: 'Home'),
            TabItem(icon: Icons.map, title: 'Discover'),
            TabItem(icon: Icons.search, title: 'Busca'),
            TabItem(icon: Icons.person, title: 'Mi Cuenta'),
            TabItem(icon: Icons.build, title: 'Settings'),
          ],
          initialActiveIndex: 2, //optional, default as 0
          onTap: (int i) => print('click index=$i'),
        ));
  }
}
于 2020-10-30T05:57:04.633 に答える