代码之家  ›  专栏  ›  技术社区  ›  Waza_Be

flatter不想导入json

  •  0
  • Waza_Be  · 技术社区  · 6 年前

    https://flutter.io/cookbook/networking/fetch-data/

    因此,我在pubspec.yaml中添加了以下行:

    dependencies:
      flutter:
        sdk: flutter
    
      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^0.1.2
    
      http: 0.11.3+17
    
      json_annotation: ^0.2.3
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
    
      build_runner: ^0.9.0
    
      json_serializable: ^0.5.4
    

    在编译时,我遇到了一个错误。

    编译器消息:lib/main。dart:53:26:错误:找不到方法: return Post.fromJson(json.decode(response.body));

    知道我做错了什么吗? 这是我的密码:

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo2',
          theme: new ThemeData(
            primarySwatch: Colors.amber,
          ),
          home: new MyHomePage(title: 'Islam Essentiel'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    
    class Post {
      final int userId;
      final int id;
      final String title;
      final String body;
    
      Post({this.userId, this.id, this.title, this.body});
    
      factory Post.fromJson(Map<String, dynamic> json) {
        return Post(
          userId: json['userId'],
          id: json['id'],
          title: json['title'],
          body: json['body'],
        );
      }
    }
    
    Future<Post> fetchPost() async {
      final response =
      await http.get('https://jsonplaceholder.typicode.com/posts/1');
    
      if (response.statusCode == 200) {
        // If server returns an OK response, parse the JSON
        return Post.fromJson(json.decode(response.body));
      } else {
        // If that response was not OK, throw an error.
        throw Exception('Failed to load post');
      }
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      void _incrementCounter() {
        setState(() {
    
    
        });
      }
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return new Scaffold(
          appBar: new AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: new Text(widget.title),
          ),
          body: new Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: new Column(
              // Column is also layout widget. It takes a list of children and
              // arranges them vertically. By default, it sizes itself to fit its
              // children horizontally, and tries to be as tall as its parent.
              //
              // Invoke "debug paint" (press "p" in the console where you ran
              // "flutter run", or select "Toggle Debug Paint" from the Flutter tool
              // window in IntelliJ) to see the wireframe for each widget.
              //
              // Column has various properties to control how it sizes itself and
              // how it positions its children. Here we use mainAxisAlignment to
              // center the children vertically; the main axis here is the vertical
              // axis because Columns are vertical (the cross axis would be
              // horizontal).
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Card(
                  child: new Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      const ListTile(
                        leading: const Icon(Icons.album),
                        title: const Text('al-khamis: 30. Muharram 1440'),
                        subtitle: const Text('20:51 - Icha.'),
                      ),
                      new ButtonTheme.bar( // make buttons use the appropriate styles for cards
                        child: new ButtonBar(
                          children: <Widget>[
                            new FlatButton(
                              child: const Text('MECQUE - DIRECTION'),
                              onPressed: () { /* ... */ },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          floatingActionButton: new FloatingActionButton(
        onPressed: fetchPost,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
        );
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  15
  •   Günter Zöchbauer    6 年前

    你需要导入它

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

    jsonDecode(response.body)
    

    import 'dart:convert' show json;
    

    具有

    json.decode(response.body)
    

    添加第一个变量是为了避免在命名包含JSON值的变量时发生冲突 json .