Как я могу выровнять текст префикса и курсор в одной строке в TextField Flutter, сохраняя при этом текст префикса всегдаIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Как я могу выровнять текст префикса и курсор в одной строке в TextField Flutter, сохраняя при этом текст префикса всегда

Сообщение Anonymous »

Я работаю над TextField во Flutter и пытаюсь добиться следующего:
  • Выравнивание текста по префиксу: Я хочу, чтобы текст префикса (например, «Кому:») был виден всегда, даже если пользователь не сосредоточился на TextField.
  • < strong>Выравнивание курсора: я хочу, чтобы курсор должен располагаться на той же строке, что и текст префикса, не выше и не ниже префикса.
  • Текст подсказки: мне также нужен текст подсказки (например, «Имя, $Cashtag, Телефон, Электронная почта») остаются видимыми, когда TextField пуст, но я не хочу, чтобы курсор или текст подсказки перекрывался текстом префикса.
Что у меня есть Пробовал:
  • Использование prefixText для отображения текста префикса, но это работает только тогда, когда TextField находится в фокусе и плохо совмещается с курсором.
  • Используйте prefixIcon с Padding и Align, чтобы попробовать и отрегулируйте выравнивание, но при этом курсор и текст подсказки смещаются. исчезнуть.
  • Я также пробовал установить курсорЦвет, границу: InputBorder.none и настроить отступы, но безрезультатно.
Код:

Код: Выделить всё

TextField(
cursorColor: Colors.green, // Set the cursor color
decoration: InputDecoration(
hintText: 'Name, \$Cashtag, Phone, Email',
border: InputBorder.none, // Remove the border
prefixText: 'To ', // Prefix text before input
prefixStyle: TextStyle(
color: Colors.black, // Prefix text color
fontSize: 18, // Prefix text size
fontWeight: FontWeight.bold, // Prefix text weight
),
),
)
Полный код (для контекста):

Код: Выделить всё

// payment_details_screen.dart
import 'package:cashapp/utilities/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PaymentDetailsScreen extends StatelessWidget {
const PaymentDetailsScreen({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Column(
children: [
SizedBox(
height: 8.h,
),
// Header with amount and bank selection
Padding(
padding: EdgeInsets.only(right: 12.w),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: const Icon(
Icons.close,
color: Colors.black,
size: 30,
),
onPressed: () =>  Navigator.pop(context),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'\$7,000',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Padding(
padding: EdgeInsets.only(left: 16.w),
child: InkWell(
onTap: () {
// Show bank selection
},
child: Row(
children: const [
Text(
'Cash Balance',
style: TextStyle(
color: gray2,
fontSize: 14,
),
),
Icon(Icons.keyboard_arrow_down,
color: Colors.grey),
],
),
),
),
],
),
ElevatedButton(
onPressed: () {
// Handle payment
},
style: ElevatedButton.styleFrom(
elevation: 0.0,
padding:
EdgeInsets.symmetric(horizontal: 24, vertical: 10),
backgroundColor: green3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
),
minimumSize:
Size(60, 32), // Set width to 60 and height to 32
),
child: const Text(
'Pay',
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
],
),
),
Divider(
color: gray5,
thickness: 1.5,
height: 32.h,
),
// Input fields
const SizedBox(width: 16),
TextField(
cursorColor: green3, // Set the cursor color to green
decoration: InputDecoration(
hintText: 'Name, \$Cashtag, Phone, Email',
hintStyle: TextStyle(
color: Colors.grey), // Optional, for hint text color
border: InputBorder.none, // Remove the border
prefixText: 'To ', // Prefix text before input
prefixStyle: TextStyle(
color: Colors.black, // Prefix text color
fontSize: 18, // Prefix text size
fontWeight: FontWeight.bold, // Prefix text weight
),
),
),
Divider(
color: gray5,
thickness: 1.5,
height: 32.h,
),
// Input fields
TextField(
cursorColor: green3, // Set the cursor color to green
decoration: InputDecoration(
hintText: 'Name, \$Cashtag, Phone, Email',
border: InputBorder.none, // Remove the border
prefixText: 'For ', // Prefix text before input
prefixStyle: TextStyle(
color: Colors.black, // Prefix text color
fontSize: 18, // Prefix text size
fontWeight: FontWeight.bold, // Prefix text weight
),
),
),

// Payment type selector
SingleChildScrollView(
scrollDirection:
Axis.horizontal, // Make the row scrollable horizontally
child: Row(
children: [
const Text('Send as'),
const SizedBox(width: 16),
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF24CE84),
shape:  RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: const Text('Cash'),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: () {},
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: Row(
children: const [
Text('Gift Card'),
Icon(Icons.keyboard_arrow_down),
],
),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: () {},
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: Row(
children: const [
Text('Stock'),
Icon(Icons.keyboard_arrow_down),
],
),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: () {},
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: Row(
children: const [
Text('Stock'),
Icon(Icons.keyboard_arrow_down),
],
),
),
],
),
),

// Suggested contacts
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'SUGGESTED',
style: TextStyle(
color: Colors.grey,
fontSize: 12,
),
),
const SizedBox(height: 16),
_buildContactTile(
'J',
'Jay Z',
'\$sc',
Colors.brown,
isSelected: true,
),
_buildContactTile(
'D',
'Diego',
'\$dm',
Colors.purple,
),
_buildContactTile(
'S',
'Sandy G.',
'\$sandy',
Colors.deepOrange,
),
_buildContactTile(
'J',
'Diego Martinez',
'\$dm',
Colors.purple,
),
],
),
],
),
),
);
}

Widget _buildContactTile(
String initial,
String name,
String tag,
Color avatarColor, {
bool isSelected = false,
}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: [
SizedBox(
width: 24,
height: 24,
child: Checkbox(
value: isSelected,
onChanged: (value) {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
),
),
const SizedBox(width: 12),
CircleAvatar(
backgroundColor: avatarColor,
child: Text(
initial,
style: const TextStyle(color: Colors.white),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: const TextStyle(fontWeight:  FontWeight.bold),
),
Text(
tag,
style: const TextStyle(color: Colors.grey),
),
],
),
),
const Icon(Icons.person_outline),
],
),
);
}
}

Чего я пытаюсь достичь:
введите здесь описание изображения
Во весь экран (для контекста) ):
Изображение

Проблема:
  • Текст-префикс не остается видимым, когда TextField находится в фокусе, а когда он появляется, он неправильно выровнен по курсору .
  • Курсор не отображается на том же уровне, что и текст префикса, что приводит к смещению.
    Как мне правильно выровняйте текст префикса по курсору и убедитесь, что текст префикса остается видимым, даже когда пользователь не фокусируется на TextField ?

    Подробнее здесь: https://stackoverflow.com/questions/793 ... er-textfie
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»