对Firebase的HTTP请求不起作用(颤振)

时间:2020-03-05 15:59:16

标签: firebase flutter firebase-realtime-database dart

我想向Firebase实时数据库发出发布请求。它是开放空间,因此我不需要任何身份验证。 enter image description here

当我发送发布请求时,数据确实在我的模拟器上更改,但没有添加到Firebase:still no Data After post request

这是我从中调用请求的代码(在void addNew方法中):

import 'package:flutter/material.dart';

import '../classes/transaction.dart';

import 'package:http/http.dart' as http;
import 'dart:convert';

class NewTransactions with ChangeNotifier {
  DateTime now = DateTime.now();
  double dailyBalance;
   
 List<Transaction>  dailyTransactions ;
  // double accountBalance;
  static Map<String, Transaction> _userIncome = {
      'four': Transaction(
          //dummy data
          amount: 450,
          date: DateTime.now(),
          title: 'Einkommen',
          accountType: 'Depotkonto',
          notes: 'joa',

          icon: Icon(
            Icons.today,
          ),
        
          repeat: '',
          repeatDisplayed: 'always',
          duration: 0),
      'five': Transaction(
          amount: 60,
          date: DateTime.now(),
          title: 'Bruder',
          accountType: 'Sparkasse',
          notes: 'brother',
          icon: Icon(
            Icons.today,
          ),
           repeatDisplayed: 'always',
         
          repeat: 'never',
          duration: 0),
      'six': Transaction(
          amount: 60,
          date: DateTime.now(),
          title: 'Rückerstattung',
          accountType: 'Sparkasse',
          notes: 'brother',
          icon: Icon(
            Icons.today,
          ),
           repeatDisplayed: 'always',
         
          repeat: 'never',
          duration: 0),
  };

  static Map<String, Transaction> _futureIncome = {};

  Map<String, Transaction> get futureIncome {
    return {..._futureIncome};
  }

  Map<String, Transaction> get userIncome {
    return {..._userIncome};
  }

  //--------------------------------- now come the payments maps

  static Map<String, Transaction> _userPayments = {
   
  };

  static Map<String, Transaction> _futurePayments = {};

  Map<String, Transaction> get userPayments {
    return {..._userPayments};
  }

  Map<String, Transaction> get futurePayments {
    return {..._futurePayments};
  }

//---- map for all transactions
  Map<String, Transaction> _allTransactions = {
    ..._userIncome,
    ..._userPayments,
  };

  Map<String, Transaction> get allTransactions {
    return {..._allTransactions};
  }

  Map<String, Transaction> _futereAllTransactions = {
    ..._futurePayments,
    ..._futureIncome,
  };

  Map<String, Transaction> get futereAllTransactions {
    return {..._futereAllTransactions};
  }
 

  void addNew(
      {String txTitle,
      double txAmount,
      DateTime chosenDate,
      DateTime txEnd,
      String txAccountType,
      String txNotes,
      String txRepeat,
      String txRepeatDisplayed,
      Icon txIcon,
      String txId,
      int txDuration,
      Map<String, Transaction>
          transactionType, //if I should add to income or outcome
      Map<String, Transaction> futureTransactionType}) {
    //some for here
    int y, m, d;
    const urlPay = 'https://purchase-habits.firebaseio.com/payments.json';
    const urlIn = 'https://purchase-habits.firebaseio.com/income.json';
    const urlFutureIn =
        'https://purchase-habits.firebaseio.com/futereincome.json';
    const urlFuturePay =
        'https://purchase-habits.firebaseio.com/futerepayment.json';
   
     http
        .post(txAmount < 0 ? urlPay : urlIn, body: json.encode({
        'title': 'text test',
        
      }),);
     transactionType[txTitle] = Transaction(
        title: txTitle,
        amount: txAmount,
        date: chosenDate,
        accountType: txAccountType,
        notes: txNotes,
        repeat: txRepeat,
        icon: txIcon,
        end: txEnd,
        duration: txDuration,
        repeatDisplayed: txRepeatDisplayed,
      );
 print(transactionType);
  
    notifyListeners();
   
  }

 void addNewtransaction(
      {@required String xTitle,
      @required double xAmount,
      @required DateTime xchosenDate,
      @required DateTime xEnd,
      @required String xAccountType,
      String xNotes,
      @required String xRepeat,
      @required Icon xIcon,
      @required String xId,
      @required String xRepeatDisplayed,
      @required int xDuration,
      @required String xchoiceId}) {
    //if new payment --> id of payment is 0 - income is '1'

  //  if (xchosenDate.compareTo(now) <= 0) {


  
 
      addNew(
        chosenDate: xchosenDate,
        txTitle: xTitle,
        txAmount: xchoiceId == '0' ? xAmount * (-1) : xAmount,
        txDuration: xDuration,
        txIcon: xIcon,
        txAccountType: xAccountType,
        txId: xId,
        txEnd: xEnd,
        txNotes: xNotes,
        txRepeat: xRepeat,
        transactionType: xchoiceId == '0' ? _userPayments : _userIncome,
        futureTransactionType:
            xchoiceId == '0' ? _futurePayments : _futureIncome,
        txRepeatDisplayed: xRepeatDisplayed,

      );
  //  }
     
  }

这是我的pubspec.yaml文件:

name: purchase_habit
description: A new Flutter project.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
 
  #flutter_cupertino_date_picker: ^0.0.7
  flutter:
   sdk: flutter
  provider: ^4.0.4
  intl: ^0.16.1
  flutter_picker: ^1.1.0
  carousel_slider: ^1.4.1
  page_view_indicators: ^1.3.1
  polygon_clipper: ^1.0.2
  smooth_page_indicator: ^0.1.3
  flutter_staggered_animations: ^0.1.2
  date_picker_timeline: ^1.1.3
  #workmanager: ^0.2.1
  preload_page_view: ^0.1.4
  path_provider: ^1.6.1
  http: ^0.12.0+4

 # curved_navigation_bar: ^0.3.2

  
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  fonts:
    - family: MyIcon
      fonts:
        - asset: assets/icons/MyIcon.ttf
        
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

我忘记设置某些内容了吗?还是无法将数据从模拟器传递到Firebase?你有什么建议吗?

1 个答案:

答案 0 :(得分:1)

请使您的addNew函数async并在await之前添加一个http.post,以便它等待数据被发布然后通知列表者。

示例:

void addNew({
  String txTitle,
  double txAmount,
  DateTime chosenDate,
  DateTime txEnd,
  String txAccountType,
  String txNotes,
  String txRepeat,
  String txRepeatDisplayed,
  Icon txIcon,
  String txId,
  int txDuration,
  Map<String, Transaction>
      transactionType, //if I should add to income or outcome
  Map<String, Transaction> futureTransactionType,
}) async {
  //some for here
  int y, m, d;
  const urlPay = 'https://purchase-habits.firebaseio.com/payments.json';
  const urlIn = 'https://purchase-habits.firebaseio.com/income.json';
  const urlFutureIn =
      'https://purchase-habits.firebaseio.com/futereincome.json';
  const urlFuturePay =
      'https://purchase-habits.firebaseio.com/futerepayment.json';

  await http.post(
    txAmount < 0 ? urlPay : urlIn,
    body: json.encode({
      'title': 'text test',
    }),
  );
  transactionType[txTitle] = Transaction(
    title: txTitle,
    amount: txAmount,
    date: chosenDate,
    accountType: txAccountType,
    notes: txNotes,
    repeat: txRepeat,
    icon: txIcon,
    end: txEnd,
    duration: txDuration,
    repeatDisplayed: txRepeatDisplayed,
  );
  print(transactionType);

  notifyListeners();
}

希望有帮助!