Home > OS >  i cannot solve this error. Flutter - rest api
i cannot solve this error. Flutter - rest api

Time:07-30

enter image description hereenter image description here /* The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').*/

import 'dart:core';

import 'package:flutter/material.dart';

import 'package:rest_api/data/fetch_data.dart';

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

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  int index =0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: getPost(),
        builder: (context, snapshot) {
          
          return ListView.builder(
            
            itemBuilder: (context,index){
              return Text(snapshot.**data[index]**); 
            });
        })
        
        );
  
  }
}

CodePudding user response:

The API might not give the proper response so the part of it you are trying to read might be null or non existent and Flutter has no way of knowing that the API will return a string. Try a default value if it's null like this Text(res.body.text ?? "Default")

CodePudding user response:

Try adding an exclamation mark (!):

return Text(snapshot.data![index]);

or:

return Text(snapshot.data[index] ?? "Data is null");

CodePudding user response:

You can have error from API or getting null/empty data. Check this Demo widget and configure your case. Also, the current is object is not detecting and possible to get null from. You can do.

I gues the for your case it will be

Text(snapshot.data?[index]?? "default"); 

Follow the snippet and make changes

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];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: () {
        setState(() {});
      }),
      body: 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 ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return Container(child: Text(snapshot.data[index].toString()));
              },
            );
          }

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