颤振:对话框上出现“ context!= null不正确”

时间:2020-04-16 14:16:53

标签: android flutter dialog

尝试在代码中的函数内使用对话框时遇到问题。 当我调用fetchPed函数以显示一些数据时,我只需要显示一个对话框,但是它出现了错误,我已经尝试了一些解决方法,但是我无法解决。

我遇到了错误: E/flutter ( 5257): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/localizations.dart': Failed assertion: line 446 pos 12: 'context != null': is not true.

我知道我的代码很乱,因为我现在正在测试很多东西,但是这里是:

import 'dart:convert';
import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../toasts.dart';

class Hist {
  //Classe para criar os itens
  final String codPedido;
  final String status;
  final String statusDescricao;
  final String usuario;
  final String placa;
  final String box;
  final String tipoVeiculo;
  final String dtCadastro;
  final String hrCadastro;

  Hist(
      {this.codPedido,
      this.status,
      this.statusDescricao,
      this.usuario,
      this.placa,
      this.box,
      this.tipoVeiculo,
      this.dtCadastro,
      this.hrCadastro});

  factory Hist.fromJson(Map<String, dynamic> json) {
    return Hist(
        codPedido: json['cod_pedido'],
        status: json['status'],
        statusDescricao: json['status_descricao'],
        usuario: json['usuario'],
        placa: json['placa'],
        box: json['box'],
        tipoVeiculo: json['tipo_veiculo'],
        dtCadastro: json['dt_cadastro'],
        hrCadastro: json['hr_cadastro']);
  }
}

class Ped {
  //Classe para criar os itens
  final String codPedido;
  final String status;
  final String statusDescricao;
  final String descricao;

  Ped({this.codPedido, this.status, this.statusDescricao, this.descricao});

  factory Ped.fromJson(Map<String, dynamic> json) {
    return Ped(
        codPedido: json['cod_pedido'],
        status: json['status'],
        statusDescricao: json['status_descricao'],
        descricao: json['descricao']);
  }
}

class HistListView extends StatelessWidget {
  BuildContext get context => null;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Hist>>(
      future: _fetchHist(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Hist> data = snapshot.data;
          return _histListView(data);
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        return CircularProgressIndicator();
      },
    );
  }

  // @override
  Widget build1(BuildContext context) {
    return FutureBuilder<List<Ped>>(
      future: _fetchPed(String),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Ped> data = snapshot.data;
          return _pedListView(data);
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        return CircularProgressIndicator();
      },
    );
  }

  Future<List<Hist>> _fetchHist() async {
    //Classe para carregar os pedidos da api
    //
    final prefs = await SharedPreferences.getInstance(); //pega o usuário logado
    final key = 'usuario';
    final value = prefs.getString(key);
    print('saved tester $value');
    String usu = value; //fim

    //Carrega os itens da api
    Response response = await Dio().post(
        "https://sistema.hutransportes.com.br/api/historico_pedido.php",
        data: {"usuario": usu});

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.data);
      print(response.data);
      return jsonResponse.map((job) => new Hist.fromJson(job)).toList();
    } else {
      throw Exception('Falha ao carregar histórico');
    }
  }

  Future<List<Ped>> _fetchPed(codPed) async {
    final prefs = await SharedPreferences.getInstance(); //pega o usuário logado
    final key = 'usuario';
    final value = prefs.getString(key);
    print('saved tester $value');
    String usu = value; //fim
    //Classe para carregar os itens da api
    //
    //Carrega os itens da api
    Response response = await Dio().post(
        "https://sistema.hutransportes.com.br/api/historico_itens_pedido.php",
        data: {"usuario": usu, "cod_pedido": codPed});

    if (response.statusCode == 200) {
      List jsonResponse1 = json.decode(response.data);
      print(response.data);
      // final decoded = json.decode(response.data);
      print(jsonResponse1);
      // print(jsonResponse1[0]['descricao']);
      // print(jsonResponse1[1]['descricao']);
      // List ResponseOK;
      var concatenate = StringBuffer();
      for (var i = 0; i < jsonResponse1.length; i++) {
        // print("BBB");
        print(jsonResponse1[i]['descricao']);
        // List itens = jsonResponse1[i]['descricao'];
        // print(itens);
        // ResponseOK[i] = jsonResponse1[i]['descricao'];

        concatenate.write(jsonResponse1[i]['descricao'] + " \n\n ");

        print(concatenate);

      showDialog( //**the dialog part**
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: new Text("Deseja remover o item da lista?"),
            actions: <Widget>[
              new FlatButton(
                child: new Text("Fechar"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );


      return jsonResponse1.map((job) => new Ped.fromJson(job)).toList();
    } else {
      throw Exception('Falha ao carregar histórico');
    }
  }

  ListView _pedListView(data) {
    //itens do pedido
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(data[index].descricao, data[index].statusDescricao,
              Icons.settings);
        });
  }

  ListView _histListView(data) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(data[index].codPedido + " - " + data[index].hrCadastro,
              "Status: " + data[index].statusDescricao, Icons.settings);
        });
  }

  ListTile _tile(String title, String subtitle, IconData icon) => ListTile(
        title: Text(title,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 20,
            )),
        subtitle: Text(subtitle),
        leading: Icon(
          icon,
          color: Colors.green[500],
        ),
        onTap: () {
          _fetchPed(title);
          print(title);


        },
      );
}

3 个答案:

答案 0 :(得分:0)

我认为问题在于,您一开始将getter上下文设置为null。只需删除该行。那么它将起作用。

 class HistListView extends StatelessWidget {
  //remove this line  BuildContext get context => null;

  @override

答案 1 :(得分:0)

在这样的函数中

 ListView _pedListView(data) {
    //itens do pedido
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(data[index].descricao, data[index].statusDescricao,
              Icons.settings);
        });
  }

您没有将实际上下文作为参数传递。 尝试这样的事情:

ListView _pedListView(data,context) {
    //itens do pedido
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(data[index].descricao, data[index].statusDescricao,
              Icons.settings);
        });
  }

并像这样使用它:

return _pedListView(data,context);

答案 2 :(得分:0)

尝试卸载该应用,然后再次运行。这对我有用。.如果不起作用,请在模拟器上进行测试,尝试清除模拟器数据。

相关问题