简体   繁体   English

RangeError(索引):无效值:有效值范围为空:0 错误 Flutter

[英]RangeError (index): Invalid value: Valid value range is empty: 0 Error Flutter

Can you please tell me what's the issue with my code and how to avoid showing that red screen error in my app?你能告诉我我的代码有什么问题以及如何避免在我的应用程序中显示红屏错误吗?

════════ Exception caught by widgets library ═══════════════════════════════════ The following RangeError was thrown building ChatMessage(dirty): RangeError (index): Invalid value: Valid value range is empty: 0 ════════ 小部件库捕获的异常═════════════════════════════␕══以下构建 ChatMessage(dirty) 时引发 RangeError:RangeError (index):无效值:有效值范围为空:0

My Code:我的代码:

import 'package:crypto_app/models/users.dart';
import 'package:crypto_app/pages/login.dart';
import 'package:crypto_app/services/firestoreservice.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';

void main() {
  runApp(
    FriendlyChatApp(),
  );
}

final ThemeData kIOSTheme = ThemeData(
  primarySwatch: Colors.blue,
  primaryColor: Colors.grey[100],
  primaryColorBrightness: Brightness.light,
);

final ThemeData kDefaultTheme = ThemeData(
  primarySwatch: Colors.orange,
  accentColor: Colors.orangeAccent,
);

String _name = '';

class FriendlyChatApp extends StatelessWidget {
  const FriendlyChatApp({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ChatScreen(),
    );
  }
}

class ChatMessage extends StatelessWidget {
  ChatMessage({this.text, this.animationController});
  final String text;
  final AnimationController animationController;

  @override
  Widget build(BuildContext context) {
    return SizeTransition(
      sizeFactor:
          CurvedAnimation(parent: animationController, curve: Curves.easeOut),
      axisAlignment: 0.0,
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 10.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: const EdgeInsets.only(right: 16.0),
              child: CircleAvatar(child: Text(_name[0])),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(_name, style: Theme.of(context).textTheme.headline4),
                  Container(
                    margin: EdgeInsets.only(top: 5.0),
                    child: Text(text),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> with TickerProviderStateMixin {
  final List<ChatMessage> _messages = [];
  final _textController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool _isComposing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: Theme.of(context).platform == TargetPlatform.iOS //new
            ? BoxDecoration(
                border: Border(
                  top: BorderSide(color: Colors.grey[200]),
                ),
              )
            : null,
        child: Column(
          children: [
            Flexible(
              child: ListView.builder(
                padding: EdgeInsets.all(8.0),
                reverse: true,
                itemBuilder: (_, int index) => _messages[index],
                itemCount: _messages.length,
              ),
            ),
            Divider(height: 1.0),
            Container(
              decoration: BoxDecoration(color: Theme.of(context).cardColor),
              child: _buildTextComposer(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextComposer() {
    return IconTheme(
      data: IconThemeData(color: Theme.of(context).accentColor),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 8.0),
        child: Row(
          children: [
            Flexible(
              child: TextField(
                controller: _textController,
                onChanged: (String text) {
                  setState(() {
                    _isComposing = text.isNotEmpty;
                  });
                },
                onSubmitted: _isComposing ? _handleSubmitted : null,
                decoration: InputDecoration.collapsed(
                    hintText: 'Mesajınızı Buraya Yazınız:'),
                focusNode: _focusNode,
              ),
            ),
            Container(
                margin: EdgeInsets.symmetric(horizontal: 4.0),
                child: Theme.of(context).platform == TargetPlatform.iOS
                    ? CupertinoButton(
                        onPressed: _isComposing
                            ? () => _handleSubmitted(_textController.text)
                            : null,
                        child: Text('Gönder'),
                      )
                    : IconButton(
                        icon: const Icon(Icons.send),
                        onPressed: _isComposing
                            ? () => _handleSubmitted(_textController.text)
                            : null,
                      ))
          ],
        ),
      ),
    );
  }

  void _handleSubmitted(String text) {
    _textController.clear();
    setState(() {
      _isComposing = false;
    });
    var message = ChatMessage(
      text: text,
      animationController: AnimationController(
        duration: const Duration(milliseconds: 700),
        vsync: this,
      ),
    );
    setState(() {
      _messages.insert(0, message);
    });
    _focusNode.requestFocus();
    message.animationController.forward();
  }

  @override
  void dispose() {
    for (var message in _messages) {
      message.animationController.dispose();
    }
    super.dispose();
  }
}

The issue is happening because of this line:由于这条线,问题正在发生:

CircleAvatar(child: Text(_name[0])),

You've declared the variable as:您已将变量声明为:

String _name = '';

You are trying to access the first character of an empty string using the index.您正在尝试使用索引访问空字符串的第一个字符。 To fix the issue set some value to that variable:要解决此问题,请为该变量设置一些值:

String _name = 'Random';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 flutter error : RangeError (index): Invalid value: 有效值范围为空:0 - flutter error : RangeError (index): Invalid value: Valid value range is empty: 0 Flutter:RangeError(索引):无效值:有效值范围为空:-1 - Flutter: RangeError (index): Invalid value: Valid value range is empty: -1 RangeError(索引):无效值:有效值范围为空:0 | Flutter Firebase - RangeError (index): Invalid value: Valid value range is empty: 0 | Flutter Firebase Flutter:RangeError(索引):无效值:有效值范围为空:0 - Flutter: RangeError (index): Invalid value: Valid value range is empty: 0 flutter:RangeError(索引):无效值:有效值范围为空: - flutter : RangeError (index): Invalid value: Valid value range is empty: RangeError(索引):无效值:有效值范围为空:0,Flutter - RangeError (index): Invalid value: Valid value range is empty: 0, Flutter "RangeError (index): Invalid value: Valid value range is empty: 2" with flutter carousel - "RangeError (index): Invalid value: Valid value range is empty: 2" with flutter carousel RangeError(索引):无效值:有效值范围为空:0 - Flutter - RangeError (index): Invalid value: Valid value range is empty: 0 - Flutter Flutter &quot;RangeError (index): Invalid value: Valid value range is empty: 0 with WidgetSpan - Flutter "RangeError (index): Invalid value: Valid value range is empty: 0 with WidgetSpan RangeError (index): Invalid value: Valid value range is empty: 0 in flutter Firestore - RangeError (index): Invalid value: Valid value range is empty: 0 in flutter Firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM