未找到:“dart:html”导入“dart:html”;我不需要 dart:html 我也没有使用过,但我尝试通过导入它,但错误不会发生

Posted

技术标签:

【中文标题】未找到:“dart:html”导入“dart:html”;我不需要 dart:html 我也没有使用过,但我尝试通过导入它,但错误不会发生【英文标题】:Not found: 'dart:html' import 'dart:html'; I don't need dart:html and I also didn't used, but I tried by importing it, but the error isn't going 【发布时间】:2021-09-20 08:19:43 【问题描述】:

我正在编写一个代码,在该代码中我正在使用 firebase 进行注册。包括个人资料图像在内的数据将被存储到火库中。但问题是我遇到了多个我无法解决的错误。我的应用程序甚至还没有运行一次。其中一个错误是 "import:dart:html" ,我检查了所有 dart 文件,但没有找到任何未使用的 dart:html 导入。我使用 import"dart.io" 作为术语“late File”。我也通过导入 dart:html 进行了尝试,但错误仍然相同。我也尝试删除 ProfileImage 的所有代码,但错误也仍然存在。以下是 y 代码有错误的所有文件:

错误

Launching lib\main.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
Invalid depfile: D:\Noum\Data\Uni Data\Codes\android Studio\Flutter\firebase_flutter_app\.dart_tool\flutter_build\040ba043425f685efe2a35025cf4d63f\kernel_snapshot.d
Invalid depfile: D:\Noum\Data\Uni Data\Codes\Android Studio\Flutter\firebase_flutter_app\.dart_tool\flutter_build\040ba043425f685efe2a35025cf4d63f\kernel_snapshot.d
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/storage.dart:2:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/utils.dart:2:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3/lib/js.dart:8:1: Error: Not found: 'dart:js'
export 'dart:js' show allowInterop, allowInteropCaptureThis;
^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3/lib/js_util.dart:8:1: Error: Not found: 'dart:js_util'
export 'dart:js_util';
^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart:340:25: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
 - 'Auth' is from 'package:firebase/src/auth.dart' ('/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
    final nextWrapper = allowInterop((firebase_interop.UserJsImpl? user) 
                        ^^^^^^^^^^^^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart:344:26: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
 - 'Auth' is from 'package:firebase/src/auth.dart' ('/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
    final errorWrapper = allowInterop((e) => changeController.addError(e));
                         ^^^^^^^^^^^^
/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart:374:9: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
 - 'Auth' is from 'package:firebase/src/auth.dart' ('/C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/firebase-9.0.1/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
        allowInterop((firebase_interop.UserJsImpl? user) 
        ^^^^^^^^^^^^


FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 43s
Exception: Gradle task assembleDebug failed with exit code 1

颤振医生

PS C:\Users\Nouma> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [Version 10.0.19042.1052], locale en-PK)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] VS Code (version 1.57.1)
[√] Connected device (2 available)

• No issues found!
PS C:\Users\Nouma>

依赖关系

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^2.0.0
  firebase_core: ^1.3.0
  auth_buttons: ^1.0.1+4
  cloud_firestore: ^2.3.0
  firebase_storage: ^9.0.0
  google_sign_in: ^5.0.4
  firebase_analytics: ^8.1.2
  image_picker: ^0.8.1+3
  shared_preferences: ^2.0.6

Register.dart ,这是编写所有代码的文件

import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase/firebase.dart';
import 'package:firebase_auth/firebase_auth.dart' as route;
import 'package:firebase_flutter_app/ErrorAlertDialog.dart';
import 'package:firebase_flutter_app/StoreHome.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';
import 'CustomTextField.dart';
import 'LoadingDialog.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Register extends StatefulWidget 
  const Register(Key? key) : super(key: key);

  @override
  _RegisterState createState() => _RegisterState();


class _RegisterState extends State<Register> 
  final TextEditingController _nametextEditingController=TextEditingController();
  final TextEditingController _emailtextEditingController=TextEditingController();
  final TextEditingController _passwordtextEditingController=TextEditingController();
  final TextEditingController _cPasswordEditingController=TextEditingController();
  final GlobalKey<FormState> _globalKey=GlobalKey<FormState>();
  String userImageurl="";
   late File _imagefile;
  final _picker=ImagePicker();
  static final String userID='uid';
  static final String userName='name';
  static final String userEmail='email';
  static final String userAvatar='url';
  static final String userPhotoUrl='photoUrl';
  static final String userCartList='userCart';
  SharedPreferences sharedPreferences=SharedPreferences.getInstance() as SharedPreferences;


  @override
  Widget build(BuildContext context) 

    double _screenwidth=MediaQuery.of(context).size.width;
    return SingleChildScrollView(
      child: Container(
        child: Column(
          mainAxisSize:MainAxisSize.max,
          children: [
            SizedBox(height: 10.0,),
            InkWell(
              onTap:(),
              child: CircleAvatar(
                radius: _screenwidth *0.15,
                backgroundColor: Colors.white30,
                // ignore: unnecessary_null_comparison
                child: Icon(Icons.add_a_photo_outlined,size: _screenwidth *0.15,color: Colors.grey,),
                //backgroundImage: _imagefile==null ? null: FileImage(_imagefile),
                // ignore: unnecessary_null_comparison
               // child: _imagefile==null ? Icon(Icons.add_a_photo_outlined,size: _screenwidth *0.15,color: Colors.grey,)
               // :null,

              ),
            ),
            SizedBox(height: 8.0,),
            Form(
                key: _globalKey,
                child:Column(
                  children: [
                    CustomTextField(
                    controller: _nametextEditingController,
                      data: Icons.person,
                      hintText: 'Name',
                      isObsecure: false,
                    ),
                    CustomTextField(
                      controller: _emailtextEditingController,
                      data: Icons.email,
                      hintText: 'Email',
                      isObsecure: false,
                    ),
                    CustomTextField(
                      controller: _passwordtextEditingController,
                      data: Icons.password,
                      hintText: 'Password',
                      isObsecure: true,
                    ),
                    CustomTextField(
                      controller: _cPasswordEditingController,
                      data: Icons.password,
                      hintText: 'Confirm Password',
                      isObsecure: true,
                    ),
                  ],
                )
            ),
            RaisedButton(
                onPressed: ()
                
                //  uploadAndSaveImage();
                ,
              color: Colors.blueGrey,
              child: Text('Sign Up',style: TextStyle(color: Colors.white30),),
            ),
            SizedBox(
              height: 30.0,
            ),
            Container(
              height: 4.0,
              width: _screenwidth* 0.8,
              color: Colors.cyan,
            ),
            SizedBox(
              height: 15.0,
            ),
          ],
        ),
      ),
    );
  
   Future<void> _selectAndPickImage() async // ignore: unused_element
  

    _imagefile = (await _picker.getImage(source: ImageSource.gallery) )as File;
  

  Future<void> uploadAndSaveImage()async
  
   // ignore: unnecessary_null_comparison
   if(_imagefile==null)
     
       showDialog(
           context: context,
           builder:(c)
           
            return ErrorAlertDialog(message: 'Please Select an Image');

           
       );
     
   else
     
       _passwordtextEditingController.text==_cPasswordEditingController.text
       // ? is an 'if' condition
       //if all these are true we will upload the image
           ? _emailtextEditingController.text.isNotEmpty
           && _passwordtextEditingController.text.isNotEmpty
           && _cPasswordEditingController.text.isNotEmpty
           &&_nametextEditingController.text.isNotEmpty


           ? uploadToStorage()

       //this dialogue is for the upper fields if they remains somehow empty
           :displayDialog('Please fill the empty fields in form...')
           :displayDialog('Password do not match');

     
  
  displayDialog(String msg)
  
    showDialog(context: context,
        builder: (C)
    
      return ErrorAlertDialog(message: msg);
    
    );
  
  uploadToStorage()async
  
    showDialog(
        context: context,
        builder: (c)
          return LoadingDialog(mesage: 'Authenticating, Please Wait!...',);
        

    );
    //unique name to upload it to firestore,and we will use datetime sp it won't repeat again
    String imageFileName=DateTime.now().millisecondsSinceEpoch.toString();

    StorageReference storageReference=FirebaseStorage.instance.ref().child(imageFileName) as StorageReference;
    var uploadTask=storageReference.put(_imagefile);
    UploadTaskSnapshot taskSnapshot=await uploadTask.future;

    await taskSnapshot.ref.getDownloadURL().then((urlimage)
      userImageurl=urlimage as String;

      _registerUser();

    );



  
  route.FirebaseAuth _auth=route.FirebaseAuth.instance;
  void _registerUser() async
  
    route.User? userr;
    await _auth.createUserWithEmailAndPassword(
      email: _emailtextEditingController.text.trim(),
      password: _passwordtextEditingController.text.trim(),
    ).then((auth) 
       userr = auth.user!;
    ).catchError((error) 
      Navigator.pop(context);
      showDialog(
          context: context,
          builder: (c) 
            return ErrorAlertDialog(message: error.toString(),);
          
      );
    );
    if (userr != null)
  
     saveUserInfoToFirestore(userr!).then((value)
     Navigator.pop(context);
     //if the user registration gets successful we will send it to store home
     Route route=MaterialPageRoute(builder: (c)=>StoreHome());
     Navigator.pushReplacement(context, route);
     );

  
  
  Future saveUserInfoToFirestore(route.User firebaseUser) async
  
    FirebaseFirestore.instance.collection('users').doc(firebaseUser.uid).set(
      'uid':firebaseUser.uid,
      'email':firebaseUser.email,
      'name':_nametextEditingController.text.trim(),
      'url':userImageurl,
    );
    await sharedPreferences.setString('uid', firebaseUser.uid);
    await sharedPreferences.setString(userEmail, firebaseUser.email.toString());
    await sharedPreferences.setString(userName, _nametextEditingController.text.trim());
    await sharedPreferences.setString(userAvatar, userImageurl);
    await sharedPreferences.setStringList(userCartList, ["garbageValue"]);
  




ma​​in.dart 文件:这里我使用 dart:async 作为方法“时间”

//import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:firebase/firestore.dart';

import 'dart:async';    
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

//import 'package:shared_preferences/shared_preferences.dart';

import 'AuthenticationScreen.dart';
import 'StoreHome.dart';

void main() async
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  //SharedPreferences sharedPreferences=SharedPreferences.getInstance() as SharedPreferences;
  //Firestore firestore=FirebaseFirestore.instance as Firestore;
  // ignore: unnecessary_statements

  runApp(MyApp());


class MyApp extends StatelessWidget 
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) 

    return MaterialApp(
      title: 'E-Shop',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: SplashScreen(),
    );
  

class SplashScreen extends StatefulWidget
  @override
  State<StatefulWidget> createState() => _splashproperties();
//=>(Fat Arrow is used to replace the braces and return)


class _splashproperties extends State<SplashScreen>
  @override
  void initState()
    super.initState();
    displaySplash();
  
  displaySplash()
    FirebaseAuth auth=FirebaseAuth.instance;
    Timer(Duration(seconds: 5), () async
      if(auth.currentUser!= null)
      
        Route route=MaterialPageRoute(builder: (_)=>StoreHome());
        Navigator.pushReplacement(context, route);
      
      else
        Route route=MaterialPageRoute(builder: (_)=>AuthenticationScreen());
        Navigator.pushReplacement(context, route);
      
    );
  


  Widget build(BuildContext context) 
    return Material
      (
      child: Container
        (
        decoration: new BoxDecoration(
            gradient: new LinearGradient(colors:[Colors.pink,Colors.lightGreenAccent],
              begin: const FractionalOffset(0.0, 0.0),
              end: const FractionalOffset(1.0, 0.0),
              stops: [0.0,1.0],
              tileMode: TileMode.clamp,
            )
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset('images/xweb.jpg'),
              SizedBox(height: 20.0),
              Text("Number One We Are!!!!!!!",style: TextStyle(color: Colors.white30),
              ),
            ],
          ),
        ),
      ),
    );
  


【问题讨论】:

我也有同样的情况,这个答案帮助了我:Answer 【参考方案1】:

尝试清理软件包并再次运行 pub get

flutter clean
./gradlew clean
flutter pub get

如果不起作用,请尝试this

【讨论】:

我重新安装了Android Studio,假设某些东西可能卡在工作室内存或缓存中的某个地方,然后我做了flutter clean,pub缓存修复,我删除了所有依赖项并再次发布了依赖项,我甚至尝试通过删除 pubspec.lock 文件,但错误没有移动一英寸。

以上是关于未找到:“dart:html”导入“dart:html”;我不需要 dart:html 我也没有使用过,但我尝试通过导入它,但错误不会发生的主要内容,如果未能解决你的问题,请参考以下文章

错误:未找到:'dart:html' 使用带有颤振的 googleapis_auth 飞镖团队包时

dart:io 或 dart:html 的条件导入

WebStorm-Dart导入错误

如何导入依赖于 Flutter 平台的 Dart 文件或包?

如果您的项目有 dart html 导入,如何在模拟器上运行颤振

★Dart-2-Dart工具集