【问题标题】:Error: Expected a value of type 'String', but got one of type 'Null' at new note.Note.fromJson错误:需要一个“String”类型的值,但在新的 note.Note.fromJson 中得到一个“Null”类型的值
【发布时间】:2021-10-31 14:06:50
【问题描述】:

我正在观看一个视频来实现 listview builder,但遇到了上面提到的错误,我认为这是由于 null 安全性但不知道如何解决它。我正在研究 vscode 并启动 lib\main。 dart 在 Chrome 上调试模式。以下是我的完整代码:
有两个类,即 ma​​in.dartnote.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:listview/entities/note.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
   await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
var notes = <Note>[];
if (response.statusCode == 200) {
  var notesJson = jsonDecode(response.body);
  for (var noteJson in notesJson) {
    notes.add(Note.fromJson(noteJson));
  }
}
return notes;
  }

  @override
  Widget build(BuildContext context) {
    fetchNotes().then((value) {
      _notes.addAll(value);
    });
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text("Listview with Json"),
            ),
            body: ListView.builder(
              itemBuilder: (context, index) {
                return Card(
                  child: Padding(
                    padding: const EdgeInsets.only(
                        top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          _notes[index].title,
                          style: TextStyle(
                              fontSize: 22, fontWeight: FontWeight.bold),
                        ),
                        Text(
                          _notes[index].text,
                          style: TextStyle(color: Colors.grey.shade700),
                        )
                      ],
                    ),
                  ),
                );
              },
              itemCount: _notes.length,
            )));
  }
}


class Note {
  late String title;
  late String text;

  Note(this.title, this.text);
  Note.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    text = json['text'];
  }
}

【问题讨论】:

  • 这是我关注的视频的 url:youtu.be/Fo04xk9gIFo 我认为我的错误是由于 null 安全性或 json 占位符 @RavindraS.Patil 的 url
  • 查看我的回答希望对你有帮助

标签: flutter dart dart-null-safety flutter-futurebuilder flutter-listview


【解决方案1】:

试试下面的代码你的问题已经解决了

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

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);
  Future<List<dynamic>> getInfoData() async {
    String url = 'https://jsonplaceholder.typicode.com/posts';
    var response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: FutureBuilder<List<dynamic>>(
            future: getInfoData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      var id = snapshot.data![index]['id'];
                      var userid = snapshot.data![index]['userId'];
                      var title = snapshot.data![index]['title'];
                      var body = snapshot.data![index]['body'];

                      return Card(
                        shape: RoundedRectangleBorder(
                          side: BorderSide(
                            color: Colors.green.shade300,
                          ),
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        child: ListTile(
                          leading: Text(id.toString()),
                          title: Text(title),
                          subtitle: Text(body),
                          trailing: Text(userid.toString()),
                        ),
                      );
                    },
                  ),
                );
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

你的屏幕结果 ->

【讨论】:

  • 请您编辑我的代码以删除错误而不是复制粘贴,我的代码结构与@Ravindra S. Patil 不同
  • 尝试在您的代码中更改 text = json['body']; 而不是 text = json['text'];
猜你喜欢
  • 2021-09-18
  • 2022-01-08
  • 2021-09-13
  • 2021-12-04
  • 2021-06-06
  • 2021-12-27
  • 2022-06-27
  • 2021-10-23
  • 1970-01-01
相关资源
最近更新 更多