Home > OS >  flutter error runes isnt a fuction or method and cant be invoked
flutter error runes isnt a fuction or method and cant be invoked

Time:12-17

enter image description here

List posts=[];

Future getPost()async{
    
    var url="https://jsonplaceholder.typicode.com/posts" ; 
    var http;
    var response = await http.get(url);             
    var responsebody = jsonDecode(response.body) ;       
    return responsebody ; 
    // ignore: dead_code
    setState(() {
      posts.addAll(responsebody);
    });
    }
    @override
    void initState() {
      getPost();
      super.initState();
      
    }



// ignore: dead_code
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title:Text('Alex',style: TextStyle(color: Colors.cyanAccent),),
backgroundColor: Colors.black87,centerTitle: true,),
        drawer: Drawer(),
        body: posts == null || posts.isEmpty ? Center(child: CircularProgressIndicator(),) :
                Center( child: ListView.builder(
                   itemCount : posts.length,
                   itemBuilder :(context,i){
                         return Text("${posts[i]['title']}");

                   }
                 
                 ,)
            ));

          }}

CodePudding user response:

Add this class

class MyClass {
  final int userId;
  final int id;
  final String title;
  final String body;

  MyClass(
    this.userId,
    this.id,
    this.title,
    this.body);
  factory MyClass.fromMap(Map<String, dynamic> json) {
    return MyClass(
      json['userId'],
      json['id'],
      json['title'],
      json['body']);
  }
}

then change getPost() method to :

import 'package:http/http.dart' as http;
Future getPost()async{
    
    var url="https://jsonplaceholder.typicode.com/posts" ; 
    var response = await http.get(url);
    
    final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
   
   
   
    setState(() {
       posts = parsed
        .map<MyClass>((json) => MyClass.fromMap(json))
        .toList();
    });
}

CodePudding user response:

The problem is with SDK tools so go to ur cmd znd type: git clean -xfd Restart ur computer than type: Flutter upgrade

  • Related