Home > OS >  FutureBuilder operated without initState in flutter
FutureBuilder operated without initState in flutter

Time:07-30

I work with FutureBuilder to view a set of data through GridView by FutureBuilder but there are one problem the data is view without put method in initState().I don't know why it works without putting it in initState().

full code:

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  bool showicon = false;
  var apiURL;
  Future getdataCat() async {
    setState(() {
      showicon = true;
    });
    apiURL = '***********************';
    var response = await http.post(Uri.parse(apiURL));
    var responsebody = jsonDecode(response.body);
    if (responsebody.length > 0) {
      return responsebody;
    } else {
      showicon = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Flexible(
              child: FutureBuilder(
                future: getdataCat(),
                builder: (context, AsyncSnapshot snapshot) {
                  if (!snapshot.hasData) {
                    // still waiting for data to come
                    return showicon
                        ? Center(
                            child: CircularProgressIndicator(
                            color: Colors.black,
                          ))
                        : SizedBox(
                            height: 10,
                            child: Center(
                                child: Image.asset(
                              'assets/data.png',
                            )));
                  } else if (snapshot.hasData &&
                      snapshot.data.isEmpty &&
                      snapshot.data <= 0) {
                    return SizedBox(
                        height: 10,
                        child: Center(
                            child: Image.asset(
                          'assets/data.png',
                        )));
                  } else {
                    return GridView.builder(
                      physics: ScrollPhysics(),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, childAspectRatio: 3.4),
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return Container(
                          child: Card(
                            child: Column(
                              children: <Widget>[
                                Flexible(
                                    child: GestureDetector(
                                  child: Column(children: <Widget>[
                                    Center(
                                        child: Text(
                                            "${snapshot.data[index]['name']}"))
                                  ]),
                                )),
                              ],
                            ),
                          ),
                        );
                      },
                    );
                  }
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

As you can see I not make any thing in initState() but it's still working.

I need to stop it if I don't put it in initState().Because I need to run a different function before it.

CodePudding user response:

Point of FutureBuilder is to run a function that will return with the data you want to use to build your widgets.

You already call your method in the FutureBuilder:

FutureBuilder(
   future: getdataCat(),
   builder: (context, AsyncSnapshot snapshot) {...}
)

CodePudding user response:

I prefer this way. You can check Randal L. Schwartz video

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final Future<List<int>?> myFuture;
  @override
  void initState() {
    super.initState();
    myFuture = getCatData();
  }

  Future<List<int>?> getCatData() async {
    await Future.delayed(Duration(seconds: 2));
    //your operations

    return [1, 2, 5];
    // return [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: () {
        setState(() {});
      }),
      body: Center(
        child: Column(
          children: <Widget>[
            Flexible(
              child: FutureBuilder<List<int>?>(
                future: myFuture,
                builder: (context, AsyncSnapshot snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const CircularProgressIndicator();
                  }

                  if (snapshot.hasError) {
                    return Text("Error ${snapshot.error}");
                  }
                  if (!snapshot.hasData) {
                    return Text("no Data found");
                  }
                  if (snapshot.data!.isEmpty) {
                    return Text("Empty found");
                  }

                  if (snapshot.hasData) {
                    return GridView.builder(
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: 3.4,
                      ),
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return Container(
                            child: Text(snapshot.data[index].toString()));
                      },
                    );
                  }

                  return Text("NA");
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}
  • Related