Search code examples
dartflutterflutter-sliver

How to pass List _data from main() to Stateful widget (LIstView)?


I want to access _data from main() async to Stateful Widget? Is it good practice to call REST Api Call in Main()?

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

Future main() async {

  List _data = await makeRequest();
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}
Future<List> makeRequest() async {
  String url = "https://jsonplaceholder.typicode.com/posts";
  http.Response response = await http.get(url);
  print(json.decode(response.body));
  return json.decode(response.body);
}
class HomePage extends StatefulWidget {


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

class _HomePageState extends State<HomePage> {

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("JSON List"),
      ),

      body: ListView.builder(
          itemBuilder: (BuildContext context, int index) {
             ListTile(
            );
      }
      ),
    );
  }


}

Solution

  • This is how it should works, I fixed your code :

      class HomePage extends StatefulWidget {
        @override
        _HomePageState createState() => _HomePageState();
      }
    
      class _HomePageState extends State<HomePage> {
        List _data = new List();
    
        void makeRequest() async {
          String url = "https://jsonplaceholder.typicode.com/posts";
          http.Response response = await http.get(url);
          print(json.decode(response.body));
          setState(() {
            _data = json.decode(response.body) as List;
          });
        }
    
        @override
        void initState() {
          makeRequest();
          super.initState();
        }
    
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text("JSON List"),
            ),
            body: _data.isEmpty
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemCount: _data.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        title: Text(_data[index]['title']),
                      );
                    }),
          );
        }
      }
    

    your main call should be

    void main() => runApp(MyApp());
    
    
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            home: HomePage(),
          );
        }
      }