Флаттер: "context! = Null is true" в диалоговом окне - PullRequest
0 голосов
/ 16 апреля 2020

У меня проблема при попытке использовать диалог внутри функции в моем коде. Мне просто нужно показать диалоговое окно, когда я вызываю свою функцию 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);


        },
      );
}

Ответы [ 2 ]

0 голосов
/ 16 апреля 2020

В подобных функциях

 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);
0 голосов
/ 16 апреля 2020

Я думаю, проблема в том, что вы вначале устанавливаете контекст getter на null. просто удали эту строку. тогда это будет работать.

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

  @override
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...