Flutter SnackBar没有显示

时间:2019-12-05 06:37:08

标签: android flutter

我已经实现了一个表单提交功能。提交后我想要SnackBar Alert。我已经尝试过,但是不起作用。添加SnackBar后,路由也不起作用。

addTicket() async {
if (_formKey.currentState.validate()) {
  _formKey.currentState.save();

  try{
    DocumentReference ref = await db.collection('CostalLineTicketDetails').
    document(ticketCato).collection("Tickets").add(
        {
          'startStation':startStation,
          'endStation':endStation,
          'price':price,
          'ticketType':ticketCato,
          'contactNo':contactNo,
          'dateTime':dateTime,
        });
    setState(() => id = ref.documentID);
    Navigator.push(context, new MaterialPageRoute(builder: (context) => CostalLine()));

    Scaffold.of(context).showSnackBar(SnackBar(content: Text('Ticket Added Sucessfully')));

  }catch(e){
    print(e);
  }
}

} }

3 个答案:

答案 0 :(得分:1)

尝试一下

addTicket() async {
if (_formKey.currentState.validate()) {
  _formKey.currentState.save();

  try{
    DocumentReference ref = await 
    db.collection('CostalLineTicketDetails').
    document(ticketCato).collection("Tickets").add(
        {
          'startStation':startStation,
          'endStation':endStation,
          'price':price,
          'ticketType':ticketCato,
          'contactNo':contactNo,
          'dateTime':dateTime,
        });
    setState(() => id = ref.documentID);
   // Navigator.push(context, new MaterialPageRoute(builder: (context) => CostalLine()));

    Scaffold.of(context).showSnackBar(SnackBar(content: 
    Text('Ticket Added Sucessfully')));

  }catch(e){
    print(e);
   }
   }
   }
   } 

答案 1 :(得分:1)

  1. 转到另一个屏幕后,您无法在同一页面上显示showSnackBar
  2. 您可以这样声明_scaffoldKey并将其传递给Scaffold
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Scaffold(
      key: _scaffoldKey,

然后打开这样的小吃店

_scaffoldKey.currentState.showSnackBar(SnackBar(
        content: Text(
         'Welcome',
        ),
        duration: Duration(seconds: 2),
      ));

输出:

enter image description here


修改

您也可以在不需要每次通过_scaffoldKey的地方使用FlushBar

示例:

 Flushbar(
           title:  "Hey SuperHero",
           message:  "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
           duration:  Duration(seconds: 3),              
                )..show(context);

答案 2 :(得分:0)

在任何通用的dart文件中定义此代码,您可以在任何地方调用此函数,并且将显示通用类型的脚手架。

import React, { Component } from 'react';
    import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
    import axios from 'axios';
    import Constants from '../constants/Constants';
    import AsyncStorage from '@react-native-community/async-storage';

    export default class FreelancerScreen extends Component {
        constructor(props) {
            super(props);
            this.state = {
                dataSource: [],

                //-test
                totalBooked: null,
                dateStart: null,
            };
            console.log('Constructor()');
        }

        componentDidMount() {
            this.getAppointmentList();
            console.log('ComponentDidMount()')
        }

        getAppointmentList = () => {
            var self = this;
            axios({
                method: 'get',
                url: Constants.API_URL + 'appointment_f/flist/',
                responseType: 'json',
                headers: {
                    'X-API-KEY': 'zzzz',
                    Authorization: AsyncStorage.getItem('my_token'),
                },
            })
                .then(function (response) {
                    console.log('Response Data: ', response.data);
                })
                .catch(function (error) {
                    console.log('Error Response: ', error.response);
                });
        };

        clearAsyncStorage = async () => {
            AsyncStorage.clear();
            this.props.navigation.navigate('SignIn');
            console.log('Logged Out.')
        }

        render() {
            const { dataSource } = this.state;
            return (
                <View>
                    <Text style={{ marginLeft: 20 }}> FreelancerScreen </Text>
                    <TouchableOpacity onPress={() => this.clearAsyncStorage()}>
                        <Text style={{ margin: 20, fontSize: 25, fontWeight: 'bold' }}>LogOut</Text>
                    </TouchableOpacity>
                    {<FlatList
                        data={dataSource}
                        renderItem={({ item }) => {
                            return (
                                <View>
                                    <Text style={{ marginLeft: 20 }}>date_start: {item.date_start}</Text>
                                    <Text style={{ marginLeft: 20 }}>total_booked: {item.total_booked}</Text>
                                </View>
                            );
                        }}
                    />}
                </View>
            );
        }
    };



    /*data: {
        total_booked: this.state.totalBooked,
        date_start: this.state.dateStart,
    },*/