簡體   English   中英

Flutter:http 獲取請求在 apk 版本上不起作用

[英]Flutter: http get request doesn't work on apk release

關於我的問題有幾個類似的問題,但所有這些問題中給出的解決方案都對我不起作用,所以我嘗試用我的問題的詳細信息打開另一個問題。 我希望有人可以幫助我。

背景:我正在學習 flutter 和 dart,作為初學者,我想實現一個使用 CRUD 操作的簡單應用程序。 我使用 REST API 來訪問 MongoDB 上的數據。

問題:當我在 web 服務器上調試我的代碼作為 web 應用程序時,它工作正常。 當我嘗試使用 apk 在 Android 設備上使用 go 時,服務器似乎沒有收到 https 獲取請求,並且客戶端阻止了負載指示器。 正如其他問題中所建議的那樣,我確保在 AndroidManifest.xml 中設置了用於 INTERNET 的 android uses_permissions。* 我很確定這一點,因為 Z80791B3AE7002AFACB88C246876D 插入數據的請求也可以正常工作。 此外,我使用 https,如下所示。

要構建 apk,我使用以下命令:

flutter build apk 

我也按照其他問題的建議嘗試了這個:

flutter build apk --no-shrink

這無濟於事。

這是用於在后台獲取數據的小部件 ViewStoricoRifornimenti,(如 flutter dev 上的演示):

Future<List<Rifornimento>> fetchWelcomes(http.Client client) async {
    final response = await client.get(
      Uri.parse('https://car-statistics.herokuapp.com/rifornimenti'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        'Access-Control-Allow-Origin': '*'
      },
    );

    // Use the compute function to run parsePhotos in a separate isolate.
    return compute(parseWelcomes, response.body);
  }

  List<Rifornimento> parseWelcomes(String responseBody) {
    final parsed = Welcome.fromRawJson(responseBody);
    return parsed.data;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Rifornimento>>(
        future: fetchWelcomes(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? StoricoRifornimenti(items: snapshot.data!)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

這是顯示結果的小部件:

class _MyHomePageState extends State<MyHomePage> {

  ViewStoricoRifornimenti vsr = new ViewStoricoRifornimenti(title: "Wow");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Text('Menu'),
            ),
            ListTile(
              title: Text('Storico Rifornimenti'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => vsr),
                );
              },
            ),
          ],
        ),
      )
  }
}

難道我做錯了什么? 為什么在 Web 應用程序的調試中我沒有錯誤,而在設備上我無法獲得 http 響應?

我怎么能調試這種問題?

謝謝大家會幫助我。

確保將以下代碼添加到清單中。

首先,確保您將 Internet 權限添加到清單

 <uses-permission android:name="android.permission.INTERNET" />

秒確保您添加了 usesCleartextTraffic true ,這將確保如果您的 API 端點不安全,您仍然可以調用 API。

<application
    android:usesCleartextTraffic="true">

遵循官方遷移步驟:

官方文檔

我不得不調整 linting 設置以強制執行沒有隱式類型轉換。 在發布版本中似乎處理方式不同。

我運行了flutter pub add lints --dev來警告我的 model 類中的序列化行fromJsontoJson中的隱式類型轉換,這解決了問題。

我開始向我的項目根目錄添加一個名為analysis_options.yaml的文件,其內容如下:

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

lints package 似乎有這個甚至更多的規則。

我認為您的問題是,從 Android 9 開始,您需要在 android/res/ 文件夾中的 xml 目錄中添加一個 network_security_config.xml 文件。

network_security_config.xml的內容如下:

<domain-config cleartextTrafficPermitted="true">
  <domain includeSubdomains="true">yourdomain.com</domain>
  <domain includeSubdomains="true">yourdomain2.com</domain>
</domain-config>

有關更多信息,請訪問本文: 修復明文流量

在您的 AndroidManifest.xml 文件中的標簽內添加以下行:

android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"

這對我有用。 如果我錯了,請糾正我,並讓我知道解決了您的問題。

I have a similar problem, my app was working fine on web but not on android, I fix that by adding a null check to my class.fromMap():

class(id: json["id"] ?? '',);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM