I / flutter(26976):类型'bool'不是类型'Widget'的子类型

时间:2020-07-16 04:00:42

标签: flutter

我试图获取总价。我的情况是这样的:

在这种情况下,我涉及2个页面(我想是因为该页面中的错误表明彼此相关)。在我的menuUser.dart中,我已将图标(就像购物车一样,但不是因为我没有从事电子商务项目)放在此dart文件中,因为我已经放置了默认标签。因此,我只是将图标放在注销图标旁边。

因此,当我单击该图标时,应该转到产品购物车页面(AttractionCalc.dart)的下一页,以更新数量并获取总价(类似于电子商务应用程序)。

我的问题是,当我运行该应用程序时,当我单击该图标时,我在终端中收到此错误:

I/flutter (26976): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (26976): The following _TypeError was thrown building AttractionCalc(dirty, state:
I/flutter (26976): _AttractionCalcState#57db7):
I/flutter (26976): type 'bool' is not a subtype of type 'Widget'
I/flutter (26976):
I/flutter (26976): The relevant error-causing widget was:
I/flutter (26976):   AttractionCalc file:///C:/myapp/lib/screen/menuUser.dart:97:59
I/flutter (26976): 
I/flutter (26976): When the exception was thrown, this was the stack:
I/flutter (26976): #0      _AttractionCalcState.build (package:myapp/view/attractionCalc.dart:172:31)
I/flutter (26976): #1      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter (26976): #2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter (26976): #3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter (26976): #4      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter (26976): #5      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
I/flutter (26976): #6      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
I/flutter (26976): #7      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter (26976): #8      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter (26976): #9      SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter (26976): #10     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter (26976): #14     _invoke (dart:ui/hooks.dart:261:10)
I/flutter (26976): #15     _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter (26976): (elided 3 frames from dart:async)
I/flutter (26976):
I/flutter (26976): ════════════════════════════════════════════════════════════════════════════════════════════════════

这是我的menuUser.dart代码:

import 'dart:convert';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/api.dart';
import 'package:myapp/network/network.dart';
import 'package:myapp/view/attractionCalc.dart';
import 'package:myapp/view/home.dart';
import 'package:myapp/view/budget.dart';
import 'package:myapp/view/locationMap.dart';
import 'package:myapp/view/profile.dart';
import 'package:shared_preferences/shared_preferences.dart';


class MenuUsers extends StatefulWidget {
  final VoidCallback signOut;
  MenuUsers(this.signOut);
  @override
  _MenuUsersState createState() => _MenuUsersState();
}


class _MenuUsersState extends State<MenuUsers> {
  
  signOut(){
    setState((){
      widget.signOut();
    });
  }

  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  String deviceID;

  getDeviceInfo()async{
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print("Device Info : ${androidInfo.id}");
    setState(() {
      deviceID = androidInfo.id;
    });
  }


  String name = "";
  TabController tabController;

  getPref()async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      name = preferences.getString("name");
    });
  }

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

  // total prices
  var loadingTotalPrice = false;
  var totalCart = "0";
  getTotalPrice() async {
    setState(() {
      loadingTotalPrice = true;
    });
    final response = await http.get(NetworkUrl.getTotalPrice(deviceID));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body)[0];
      String total = data['total'];
      setState(() {
        loadingTotalPrice = false;
        totalCart = total;
      });
    } else {
      setState(() {
        loadingTotalPrice = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
          child: Scaffold(
        appBar: AppBar(
          title: Text("TravB", 
          style: TextStyle(fontSize: 25,),
          ),
          backgroundColor: Colors.pink,
          actions: <Widget>[
            IconButton(
              onPressed: (){
                Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AttractionCalc()));
              },
              icon: Icon(Icons.note_add),
            ),
            IconButton(
              onPressed: (){
                signOut();
              },
              icon: Icon(Icons.lock),
            )
          ],
        ),
        body: TabBarView(
          children: <Widget>[
            Home(),
            Budget(),
            LocationMap(),
            Profile(),
          ],
          ),
        bottomNavigationBar: TabBar(
          labelColor: Colors.pink,
          unselectedLabelColor: Colors.grey,
          indicator: UnderlineTabIndicator(
            borderSide: BorderSide(
              style: BorderStyle.none
            )
          ),
          tabs: <Widget>[
            Tab(
              icon: Icon(Icons.home),
              text: "Home",
            ),
            Tab(
              icon: Icon(Icons.view_list),
              text: "Wishlist",
            ),
            Tab(
              icon: Icon(Icons.map),
              text: "Location",
            ),
            Tab(
              icon: Icon(Icons.person),
              text: "Profile",
            )
          ],
        ),
      ),
    );
  }
}

这是我的AttractionCalc.dart代码:

import 'dart:convert';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/attractionCalcModel.dart';
import 'package:myapp/network/network.dart';

class AttractionCalc extends StatefulWidget {
  @override
  _AttractionCalcState createState() => _AttractionCalcState();
}

class _AttractionCalcState extends State<AttractionCalc> {
  List<AttractionCalcModel> list = [];

  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

  getDeviceInfo()async{
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print("Device Info : ${androidInfo.id}");
    setState(() {
      unikID = androidInfo.id;
    });
    _fetchData();
  }

  String unikID;

  var loading = false;
  var cekData = false;

  _fetchData() async {
    setState(() {
      loading = true;
    });
    list.clear();
    final response = await http.get(NetworkUrl.getProductCalc(unikID));
    if (response.statusCode == 200) {
      if (response.contentLength == 2) {
        setState(() {
          loading = false;
          cekData = false;
        });
      } else {
        final data = jsonDecode(response.body);
        setState(() {
          for (Map i in data ) {
            list.add(AttractionCalcModel.fromJson(i));
          }
          loading = false;
          cekData = true;
        });
        getSummaryAmount();
      }
      
    } else {
      setState(() {
          loading = false;
          cekData = false;
      });
    }
  }

  var totalPrice = "0";
  getSummaryAmount() async {
    setState(() {
      loading = true;
    });
    final response = await http.get(NetworkUrl.getSummaryAmountCalc(unikID));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body)[0];
      String total = data['total'];
      setState(() {
        loading = false;
        totalPrice = total;
      });
    } else {
      setState(() {
        loading = false;
      });
    }
  }

  
  _addQuantity(AttractionCalcModel model, String tipe) async {
    await http.post(NetworkUrl.updateQuantity(), body: {
      "idAttraction" : model.id,
      "unikID" : unikID,
      "tipe" : tipe,
      });
    _fetchData();
  }


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


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Calculate Attraction Prices"),
        elevation: 1,
      ),
      body: Container(
        padding: EdgeInsets.all(16),
        child: loading ? Center(
          child: CircularProgressIndicator(),
        ) 
        : cekData 
        ? Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: list.length,
                shrinkWrap: true,
                physics: ClampingScrollPhysics(),
                itemBuilder: (context, i){
                  final a = list[i];
                  return Container(
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: <Widget>[
                              Text(a.attractionName),
                              Text("Price : RM ${a.price}"),
                              Container(
                                padding: EdgeInsets.symmetric(
                                  vertical: 2
                                ),
                                child: Divider(
                                  color: Colors.grey,
                                )
                              )
                            ],
                          ),
                        ),
                        Container(
                          child: IconButton(
                            onPressed: (){
                              _addQuantity(a, "tambah");
                            },
                            icon: Icon(Icons.add),
                          ),
                        ),
                        Container(
                          child: Text("${a.qty}"),
                        ),
                        Container(
                          child: IconButton(
                            onPressed: (){
                              _addQuantity(a, "kurang");
                            },
                            icon: Icon(Icons.remove),
                          ),
                        )
                      ],
                    )
                  );
                },
              ),
            ),
            totalPrice == "0" ?? SizedBox(),
            Container(
              padding: EdgeInsets.all(16),
              child: Text("Total Budget : RM ${totalPrice.toString()}"),
            )
          ],
        )
         : Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("You don't have any places to be calculate", 
            textAlign: TextAlign.center, 
            style: TextStyle(
              fontSize: 18, fontWeight: FontWeight.bold
            ),)
          ],
        )
      ),
    );
  }
}

请让我知道我哪里出了错,我是Flutter的新手。这是我的最后一年的项目,我真的需要一些帮助。

1 个答案:

答案 0 :(得分:1)

由于totalPrice == "0" ?? SizedBox(),您收到此错误。

您可以像以前一样将ternary operator用于if checks

请参见下面的代码示例:

totalPrice == "0" ? SizedBox() :  Container( padding: EdgeInsets.all(16),child: Text("Total Budget : RM ${totalPrice.toString()}"),)