Android Studio Flutter中的〈异步悬挂>

mwg9r5ms  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(192)

我是flutter的新手,当我尝试用flutter的本地通知来通知从API中获取的数据时,我遇到了一个问题,我可以获取数据,但无法获得通知。********顺便说一句,代码不完整,但至少应该可以工作
这是我主要.dart

import 'dart:async';
import 'dart:convert';
import 'notification_api.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/2'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

void main() {



  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: Column(
            children: [
              FutureBuilder<Album>(
                future: futureAlbum,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text(snapshot.data!.title);
                  } else if (snapshot.hasError) {
                    return Text('${snapshot.error}');
                  }

                  // By default, show a loading spinner.
                  return const CircularProgressIndicator();
                },
              ),
              ElevatedButton(
                onPressed: (){
                  NotificationApi.showNotification(
                    title: 'hello',
                    body: 'sup',
                  );
                },
                child: const Text("Local Notification"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这是我通知_api.dart

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationApi{
  static final _notifications = FlutterLocalNotificationsPlugin();
  static Future _notificationDetails() async{
    return const NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id',
        'channel name',
        channelDescription: 'channel description',
          importance: Importance.max
      ),
      iOS: IOSNotificationDetails(),
    );
  }
  static Future showNotification({
  int id = 0,
    String? title,
    String? body,
    String? payload,

}) async =>
      _notifications.show(
    id,
    title,
    body,
    await _notificationDetails(),
        payload: payload,
  );
}

这里是错误

E/flutter (23893): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method show on channel dexterous.com/flutter/local_notifications)
E/flutter (23893): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
E/flutter (23893): <asynchronous suspension>
E/flutter (23893): #1      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7)
E/flutter (23893): <asynchronous suspension>
E/flutter (23893):
wpx232ag

wpx232ag1#

如果你使用像await这样的词。擦除所有的词。你会看到模拟器再次工作。

相关问题