Home > Software design >  app running but in console found an exeption type 'Null' is not a subtype of type 'Ma
app running but in console found an exeption type 'Null' is not a subtype of type 'Ma

Time:08-04

I am uploading data from firebaze..its working but I noticed there is an error showing in console.

type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast

here is my code

and suggest me one thing is this okay to write code like this?

I mean the way I have created get data...


class _HomeScreenState extends State<HomeScreen> {

  bool isloaded=false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getdata();
  }

  Future<void> getdata() async {
    final url = Uri.parse(
        myjsonlink);
    final result = await http.get(url);

    setState(() {
      isloaded=true;
    });

    final data = json.decode(result.body) as Map<String, dynamic>;
    List<Transaction> _templist = [];
    data.forEach((proid, prodcutdata) {
      _templist.add(Transaction(
          id:proid,
        title: prodcutdata['title'],
        amount: double.parse(prodcutdata['amount'].toString()),
      ));
    });
    transactionlist=_templist;

    print(transactionlist);

  }


  @override
  Widget build(BuildContext context) {

    print(transactionlist.toString());
    //this showing null

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(Random().nextInt(255), 100, 100, 1),
          title: Text('Basic Demo'),
          actions: [IconButton(onPressed: () {
            Navigator.of(context).pushReplacement(
                MaterialPageRoute(builder: (context) {
                  return InputForm();
                }));
          },
              icon: Icon(Icons.add)),

            IconButton(onPressed: () {
              setState(() {

              });
            }, icon: Icon(Icons.refresh)),

          ],
        ),
        body: isloaded==false?Center(child: CircularProgressIndicator(),):Column(children: [
          transactionlist.length==0?Expanded(child: Text('No Data')):Expanded(
            child: ListView.builder(
                itemCount: transactionlist.length,
                itemBuilder: (context, index) {
                  return MyListTile(data: transactionlist[index]);
                }),

          ),

          Container(
            height: 40,
            color: Colors.red,
            child: Center(child: Text(couttotal().toStringAsFixed(2), style: TextStyle(
                fontSize: 30,
                color: Colors.white,
                fontWeight: FontWeight.bold),)),
          ),

        ],)
    );
  }

  double couttotal() {
    double amount = 0.0;
    for (int x = 0; x < transactionlist.length; x  )
      amount = amount   transactionlist[x].amount;
    return amount;
  }
}

class model


class Transaction
{
  String id;
  String title;
  double amount;

  Transaction({required this.id, required this.title,required this.amount});
}

List<Transaction> transactionlist=[];

data.forEach((proid, prodcutdata) {
      _templist.add(Transaction(
          id:proid,
        title: prodcutdata['title'],
        amount: double.parse(prodcutdata['amount'].toString()),
      ));
    });

I tried to give constant in amount:0.00 it fetching successfully..so error could be in this line...but what ?

CodePudding user response:

You are fetching data from API.

On your snippet try

Future<void> getdata() async {
/// all others operation

transactionlist=_templist;
isloaded=false;
setState((){});
}

It is better to use FutureBuilder here.

class _HomeScreenState extends State<HomeScreen> {
  Future<List<Transaction>> getdata() async {
     //....
    return _templist;
  }

  late final Future<List<Transaction>> listFuture = getdata();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       ///.. 
        body:  FutureBuilder<List<Transaction>>(
          future: listFuture,
          builder: (context, snapshot) {
          if(snapshot.hasData && snapshot.data!.isNotEmpty){
            return ListView.builder(itemBuilder: itemBuilder)
          }

          if(snapshot.hasError) return Text("error");
          return CircularProgressIndicator();
  

More about FutureBuilder

CodePudding user response:

I found MyMistake(may be it was the one)

while post I was using

http.post(url,body: json.encode({

        'title':_temptransaction.title,
        'price':_temptransaction.amount.toString()

      }))

now corrected

'price':_temptransaction.amount
  • Related