1

在我尝试本地化应用程序后,我的颤振应用程序在启动时启动闪屏后短时间内显示黑屏。而且我不确定问题出在哪里。当我删除本地化时,问题就消失了。该应用程序没有崩溃,并且在调试和发布模式下都会出现问题。我看到了这个解决方案和其他与同一主题相关的解决方案,但它们不起作用。从手机(物理和模拟器)中删除了应用程序,然后重新启动它,但它不起作用。我什至创建了一个新应用程序并将 Android 文件夹复制到旧项目,但问题没有解决。如果有人可以帮助我修复它,我将不胜感激。我按照 YouTube 上的教程进行本地化。示例应用程序也有问题。

$ flutter doctor -v
[√] Flutter (Channel stable, 1.22.6, on Microsoft Windows [Version 10.0.18363.1379], locale 
    en-US)
    • Flutter version 1.22.6 at C:\flutter
    • Framework revision 9b2d32b605 (5 weeks ago), 2021-01-22 14:36:39 -0800
    • Engine revision 2f0af37152
    • Dart version 2.10.5

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\masan\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[!] Android Studio (version 4.1.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code (version 1.53.2)
    • VS Code at C:\Users\masan\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.19.0

[!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tomson.book.deputy">
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    
    <application
        android:label="Book App"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
       
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

app_localizations.dart

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class AppLocalizations {
  final Locale locale;
  Map<String, String> _localizedStrings;
  AppLocalizations(this.locale);

  static const LocalizationsDelegate<AppLocalizations> delegate =
      _AppLocalizationsDelegate();

  ///helper method to keep the code in the widgets concise
  /////localization are accessed using an InheritedWidget 'of'
  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  ///load the language json file from the lang folder
  Future<void> load() async {
    String jsonStr =
        await rootBundle.loadString('lib/lang/${locale.languageCode}.json');

    Map<String, dynamic> jsonMap = json.decode(jsonStr);

    _localizedStrings = jsonMap.map((key, value) {
      return MapEntry(key, value.toString());
    });
  }

  ///called from every widget which needs a localized text
  String translate(String key) {
    return _localizedStrings[key];
  }
}

class _AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'fr'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localizations = new AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

  @override
  bool shouldReload(_AppLocalizationsDelegate old) => false;
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';

import 'connectivity_wrapper.dart';
import 'l10n/app_localizations.dart';
import 'services/app/app_properties.dart';
import 'services/app_theme/app_theme.dart';
import 'services/users/auth.dart';
import 'widgets/landing/get_started.dart';

//Entry point
void main() {
  Widget _defaultHome = GetStarted();

  runApp(
    MainApp(
      defaultHome: _defaultHome,
      root: buildAppRoot(_defaultHome),
    ),
  );
}

///build app root widget
Future<Widget> buildAppRoot(Widget defaultHome) async {

  ///app default theme
  var defaultTheme;

  ///reload theme from prefs
  Future<void> reloadThemeFromPrefs() {
    debugPrint("Pulling out theme id from prefs...");
  }

  await reloadThemeFromPrefs();

  return MultiProvider(
    providers: [
      ChangeNotifierProxyProvider0<AppThemeService>(
        create: (_) => AppThemeService(defaultTheme),
        update: (_, prevThemeService) =>
            AppThemeService(prevThemeService.currentTheme),
      ),
    ],
    child: Consumer<AuthService>(
      builder: (cctx, auth, _) => MaterialApp(
        key: GlobalKey(),
        //list of all supported languages
        supportedLocales: [
          Locale('en', 'US'),
          Locale('fr', 'FR'),
        ],

        localizationsDelegates: [
          AppLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],

        localeResolutionCallback: (locales, supportedLocales) {
          for (var loc in supportedLocales) {
            if (loc.languageCode == locales.languageCode &&
                loc.countryCode == locales.countryCode) {
              return loc;
            }
          }
          return supportedLocales.first;
        },
        debugShowCheckedModeBanner: false,
        title: AppProperties.appName,
        home: ConnectivityWrapper(
          child: defaultHome,
        ),
        theme: cctx.watch<AppThemeService>().currentTheme,
        routes: {},
      ),
    ),
  );
}

class MainApp extends StatelessWidget {
  final Widget defaultHome;
  final Future<Widget> root;

  const MainApp({
    this.defaultHome,
    this.root,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Widget>(
      future: root,
      builder: (_, snapshot) {
        if (snapshot.hasError) {
          return Text("${snapshot.error}");
        } else if (snapshot.hasData) {
          return snapshot.data;
        } else
          return Container(
            color: Color.fromRGBO(
              0,
              105,
              170,
              1,
            ),
          );
      },
    );
  }
}

这是问题

4

1 回答 1

1

我刚刚遇到了与您相同的问题情况,我在下面有一些观察供您参考。我猜你应用flutter_intl来启用应用程序国际化,因为在生成的 S.load 方法中存在异步未来调用可能是问题情况的根本原因。您还可以查看官方flutter.dev上的另一个国际化指南,该指南在非常相似的生成 _AppLocalizationsDelegate.load 方法中应用了 SynchronousFuture 实现以避免该问题。

于 2021-08-07T16:47:14.230 回答