【问题标题】:Flutter Set AppBar Title Using JSON Showing ErrorFlutter 使用 JSON 设置 AppBar 标题显示错误
【发布时间】:2020-06-15 07:35:28
【问题描述】:

我有一个使用 Flutter 制作的应用程序,但它显示一个错误,表明方法 [] 返回 null。

我真的不明白位置在哪里。当我在 AppBar 中设置 title 时,第一行中的 异常抛出 导致。

I/flutter ( 6601): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6601): The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePageState#b5688):
I/flutter ( 6601): The method '[]' was called on null.
I/flutter ( 6601): Receiver: null
I/flutter ( 6601): Tried calling: []("title")
I/flutter ( 6601):
I/flutter ( 6601): The relevant error-causing widget was:
I/flutter ( 6601):   HomePage                                                                                   package:blogger/main.dart:13
I/flutter ( 6601):
I/flutter ( 6601): When the exception was thrown, this was the stack:
I/flutter ( 6601): #0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:53:5)
I/flutter ( 6601): #1      _HomePageState.build                                                                 package:blogger/main.dart:47
I/flutter ( 6601): #2      StatefulElement.build                                                                package:flutter/…/widgets/framework.dart:4334
I/flutter ( 6601): #3      ComponentElement.performRebuild                                                      package:flutter/…/widgets/framework.dart:4223
I/flutter ( 6601): #4      Element.rebuild                                                                      package:flutter/…/widgets/framework.dart:3947
I/flutter ( 6601): #5      ComponentElement._firstBuild                                                         package:flutter/…/widgets/framework.dart:4206
I/flutter ( 6601): #6      StatefulElement._firstBuild                                                          package:flutter/…/widgets/framework.dart:4381
I/flutter ( 6601): #7      ComponentElement.mount                                                               package:flutter/…/widgets/framework.dart:4201
I/flutter ( 6601): #8      Element.inflateWidget 

.....

I/flutter ( 6601): #329    RenderObjectToWidgetAdapter.attachToRenderTree                                       package:flutter/…/widgets/binding.dart:941
I/flutter ( 6601): #330    WidgetsBinding.attachRootWidget                                                      package:flutter/…/widgets/binding.dart:819
I/flutter ( 6601): #331    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>                          package:flutter/…/widgets/binding.dart:804
I/flutter ( 6601): #340    _Timer._runTimers  (dart:isolate-patch/timer_impl.dart:384:19)
I/flutter ( 6601): #341    _Timer._handleMessage  (dart:isolate-patch/timer_impl.dart:418:5)
I/flutter ( 6601): #342    _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:174:12)
I/flutter ( 6601): (elided 8 frames from package dart:async and package dart:async-patch)
I/flutter ( 6601):
I/flutter ( 6601): ════════════════════════════════════════════════════════════════════════════════════════════════════

仅当我通过从 json 检索内容更改 AppBar 的标题时才会出现该错误。当我直接这样设置时,错误不会出现。从某种意义上说,这里没有错误。

 @override
  Widget build(BuildContext context) {
    return Scaffold (
      appBar: AppBar(
        title: Text("My Title"),
      ),
    );
  }

下面是我正在编写的整个程序代码。

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

import 'dart:async';
import 'dart:convert';

void main () {
  runApp(MaterialApp(
    title: "Blogger App",
    theme: new ThemeData(
      primarySwatch: Colors.yellow
    ),
    home : HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  Map data, feed;

  Future getData() async {
    http.Response response = await http.get("https://www.haliminfo.com/feeds/posts/summary/?max-results=5&alt=json");
    data = json.decode(response.body);
    setState(() {
      feed = data['feed']; 
    });
  }

  @override
  void initState() { 
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold (
      appBar: AppBar(
        title: Text(feed['title']['\$t'].toString()),
      ),
    );
  }
}

那么当我使用从互联网上获取的 JSON 更改 AppBar 上的标题时,如何确保没有错误?

谢谢

【问题讨论】:

    标签: json flutter dart flutter-appbar


    【解决方案1】:

    调用 API 调用是一个异步过程(可能需要一些时间从页面获取 JSON),因为在创建 Activity 时您的 'feed' 对象为 null 会抛出异常。

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    import 'dart:async';
    import 'dart:convert';
    
    void main () {
      runApp(MaterialApp(
        title: "Blogger App",
        theme: new ThemeData(
          primarySwatch: Colors.yellow
        ),
        home : HomePage(),
      ));
    }
    
    class HomePage extends StatefulWidget {
      HomePage({Key key}) : super(key: key);
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
    
      Map data, feed;
      String appTitle = '';
    
    
      Future getData() async {
        http.Response response = await http.get("https://www.haliminfo.com/feeds/posts/summary/?max-results=5&alt=json");
        data = json.decode(response.body);
        setState(() {
          feed = data['feed']; 
          appTitle = feed['title']['\$t'].toString();
        });
      }
    
      @override
      void initState() { 
        super.initState();
        this.getData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold (
          appBar: AppBar(
            title: Text(appTitle),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 2019-09-09
      • 1970-01-01
      • 2021-10-03
      • 2019-04-15
      • 2020-03-07
      • 2018-12-07
      • 2019-08-08
      相关资源
      最近更新 更多